package chromo;

import gene.ChinkleException;
import gene.Input;

import java.util.ArrayList;

public class Population {
	Chromosome[] chromosomes;
	
	/**
	 * Instantiates a new population using the inputs of the size populationSize
	 *
	 * @param inputs the inputs
	 * @param populationSize the population size
	 * @throws ChinkleException 
	 */
	public Population(ArrayList<Input> inputs, int populationSize) throws ChinkleException{
		chromosomes = new Chromosome[populationSize];

		for (int i = 0; i < chromosomes.length; i++) {
			chromosomes[i] = new Chromosome(inputs);
		}
	}
	
	/**
	 * Instantiates a new population but doesn't initialize it.
	 *
	 * @param populationSize the population size
	 */
	public Population(int populationSize){
		chromosomes = new Chromosome[populationSize];
		
	}
	
	/**
	 * Gets the chromosome from the population array
	 *
	 * @param index the index
	 * @return the chromosome
	 */
	public Chromosome getChromosome(int index){
		return chromosomes[index];
	}
	
	/**
	 * Sets the chromosome into the population array
	 *
	 * @param index the index
	 * @param chromo the chromo
	 */
	public void setChromosome(int index,Chromosome chromo){
		chromosomes[index] = chromo;
	}
	
	/**
	 * Calls solve for every chromosome in the population
	 *
	 * @throws TheException the the exception
	 */
	public void solve(){
		for(Chromosome chromo : chromosomes){
			chromo.solve();
		}
	}
	
	/**
	 * Size of array
	 *
	 * @return the int
	 */
	public int size() {
        return chromosomes.length;
    }
	public String toString(){
		String output = "";
		
		for(Chromosome chromo : chromosomes){
			output += chromo + "\n";
		}
		return output;
	}
	public String outputs(){
		String output = "";
		
		for(Chromosome chromo : chromosomes){
			chromo.solve();
			output += chromo.getAllOutputs() + "\n";
		}
		return output;
	}

	public Chromosome getFittest() {
		Chromosome fittest = chromosomes[0];
        // Loop through individuals to find fittest
        for (int i = 0; i < size(); i++) {
            if (fittest.getFitness() < getChromosome(i).getFitness()) {
                fittest = getChromosome(i);
            }
        }
        return fittest;
    }
}

